package cn.wolfcode.business.service.impl;

import java.math.BigDecimal;
import java.util.List;

import cn.wolfcode.business.vo.AuditInfoVO;
import cn.wolfcode.common.constant.BusinessConstants;
import cn.wolfcode.common.core.domain.entity.SysUser;
import cn.wolfcode.common.exception.ServiceException;
import cn.wolfcode.common.utils.ActivitiesUtils;
import cn.wolfcode.common.utils.DateUtils;
import cn.wolfcode.system.service.ISysUserService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.business.mapper.BusServiceItemMapper;
import cn.wolfcode.business.domain.BusServiceItem;
import cn.wolfcode.business.service.IBusServiceItemService;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.sql.rowset.serial.SerialException;

/**
 * 服务项Service业务层处理
 * 
 * @author zhangyf
 * @date 2023-04-08
 */
@Service
public class BusServiceItemServiceImpl implements IBusServiceItemService 
{
    @Autowired
    private BusServiceItemMapper busServiceItemMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private RepositoryService repositoryService;

    /**
     * 查询服务项
     * 
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public BusServiceItem selectBusServiceItemById(Long id)
    {
        return busServiceItemMapper.selectBusServiceItemById(id);
    }

    /**
     * 查询服务项列表
     * 
     * @param busServiceItem 服务项
     * @return 服务项
     */
    @Override
    public List<BusServiceItem> selectBusServiceItemList(BusServiceItem busServiceItem)
    {
        return busServiceItemMapper.selectBusServiceItemList(busServiceItem);
    }

    /**
     * 新增服务项
     * 
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int insertBusServiceItem(BusServiceItem busServiceItem)
    {
        // 参数校验问题，永远不要相信用户传递的参数都是对的
        // 6个参数都要校验
         /*参数校验的三种方式：
        1.自己写代码校验
        2.使用Spring的断言
        3.使用JDK提供的校验注解@Validated。缺点：默认注解有限，不能满足所有业务验证需求，还得要自定义注解或者混合使用
        */
        String name = busServiceItem.getName();
       /* // 方式一：
        if(!StringUtils.hasLength(name)){
            throw new ServiceException("服务项必填");
        }*/
        // 方式二：
        // Assert.hasLength(name,"服务项必填");

        /*// 这里用方式三：
        // 1.在 BusServiceItem类中添加 @NotBlank(message = "服务项不能为空")
        // 2.在BusServiceItemController类的处理方法的形参上贴@Validated*/

        BigDecimal originalPrice = busServiceItem.getOriginalPrice();
        BigDecimal discountPrice = busServiceItem.getDiscountPrice();
        /*
        // 方式1：
        if(originalPrice.compareTo(discountPrice) < 0){   // 原价小于折扣价
            throw new ServiceException("服务项原价不能小于折扣价");
        }*/
        // 方式2：
        Assert.state(originalPrice.compareTo(discountPrice) >= 0,"服务项原价不能小于折扣价");

        Integer carPackage = busServiceItem.getCarPackage();
        Integer serviceCatalog = busServiceItem.getServiceCatalog();
        String info = busServiceItem.getInfo();

        // 根据是否是套餐，设置其审核状态
            // 套餐   // 非套餐
            busServiceItem.setAuditStatus(busServiceItem.getCarPackage() == BusinessConstants.CAR_PACKAGE_YES
                    ? BusinessConstants.AUDIT_STATUS_INIT
                    : BusinessConstants.AUDIT_STATUS_NOT_NEED);

        // 设置上下架状态
        busServiceItem.setSaleStatus(BusinessConstants.SALE_STATUS_OFF);

        busServiceItem.setCreateTime(DateUtils.getNowDate());
        return busServiceItemMapper.insertBusServiceItem(busServiceItem);
    }

    /**
     * 修改服务项
     * 
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int updateBusServiceItem(BusServiceItem busServiceItem)
    {
        // 校验被修改的服务项是否存在
        Long id = busServiceItem.getId();
        Assert.notNull(id,"非法参数");

        BusServiceItem originBusServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        Assert.notNull(originBusServiceItem,"修改的服务项不存在");

        int auditStatus = originBusServiceItem.getAuditStatus();

        Assert.state(auditStatus == BusinessConstants.AUDIT_STATUS_INIT
                || auditStatus == BusinessConstants.AUDIT_STATUS_NOT_NEED,"服务项审核状态不支持修改");

        int saleStatus = originBusServiceItem.getSaleStatus();
        Assert.state(saleStatus == BusinessConstants.SALE_STATUS_OFF,"已上架的服务项不支持修改");

        BigDecimal originalPrice = busServiceItem.getOriginalPrice();
        BigDecimal discountPrice = busServiceItem.getDiscountPrice();
        Assert.state(originalPrice.compareTo(discountPrice) >= 0,"服务项原价不能小于折扣价");

        // 校验服务项的状态，表中字段有记录状态，这种的数据在修改，或者删除的时候，都要判断状态

        // 若是套餐，就设置为初始化，若不是套餐，则设置为无需审核
        busServiceItem.setAuditStatus(busServiceItem.getCarPackage() == BusinessConstants.CAR_PACKAGE_YES
                ? BusinessConstants.AUDIT_STATUS_INIT
                : BusinessConstants.AUDIT_STATUS_NOT_NEED);
        return busServiceItemMapper.updateBusServiceItem(busServiceItem);
    }

    /**
     * 批量删除服务项
     * 
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemByIds(Long[] ids)
    {
        return busServiceItemMapper.deleteBusServiceItemByIds(ids);
    }

    /**
     * 删除服务项信息
     * 
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemById(Long id)
    {
        return busServiceItemMapper.deleteBusServiceItemById(id);
    }

    @Override
    public int onSale(Long id) {
        Assert.notNull(id,"非法参数");

        BusServiceItem originBusServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        Assert.notNull(originBusServiceItem,"修改的服务项不存在");

        int auditStatus = originBusServiceItem.getAuditStatus();
        Assert.state(auditStatus == BusinessConstants.AUDIT_STATUS_NOT_NEED
                || auditStatus == BusinessConstants.AUDIT_STATUS_SUCCESS,"服务项审核状态不支持上架");

        int saleStatus = originBusServiceItem.getSaleStatus();
        Assert.state(saleStatus == BusinessConstants.SALE_STATUS_OFF,"已上架的服务项不支持上架");

        // 修改成上架状态
        originBusServiceItem.setSaleStatus(BusinessConstants.SALE_STATUS_ON);
        return  busServiceItemMapper.updateBusServiceItem(originBusServiceItem);
    }

    @Override
    public int offSale(Long id) {
        Assert.notNull(id,"非法参数");

        BusServiceItem originBusServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        Assert.notNull(originBusServiceItem,"修改的服务项不存在");

        int auditStatus = originBusServiceItem.getAuditStatus();
        Assert.state(auditStatus == BusinessConstants.AUDIT_STATUS_NOT_NEED
                || auditStatus == BusinessConstants.AUDIT_STATUS_SUCCESS,"服务项审核状态不支持下架");

        int saleStatus = originBusServiceItem.getSaleStatus();
        Assert.state(saleStatus == BusinessConstants.SALE_STATUS_ON,"已下架的服务项不支持下架");

        // 修改成下架状态
        originBusServiceItem.setSaleStatus(BusinessConstants.SALE_STATUS_OFF);
        return  busServiceItemMapper.updateBusServiceItem(originBusServiceItem);
    }

    @Override
    public int sale(Long id) {
        Assert.notNull(id,"非法参数");

        BusServiceItem originBusServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        Assert.notNull(originBusServiceItem,"修改的服务项不存在");

        int saleStatus = originBusServiceItem.getSaleStatus();
        String msg = saleStatus == BusinessConstants.SALE_STATUS_ON ? "下架":"上架";

        int auditStatus = originBusServiceItem.getAuditStatus();
        Assert.state(auditStatus == BusinessConstants.AUDIT_STATUS_NOT_NEED
                || auditStatus == BusinessConstants.AUDIT_STATUS_SUCCESS,
                "服务项审核状态不支持" + msg);

        // 我不知道到底是上架还是下架
        int newSaleStatus = saleStatus == BusinessConstants.SALE_STATUS_ON
                ? BusinessConstants.SALE_STATUS_OFF : BusinessConstants.SALE_STATUS_ON;
        originBusServiceItem.setSaleStatus(newSaleStatus);

        return  busServiceItemMapper.updateBusServiceItem(originBusServiceItem);
    }

    @Override
    public AuditInfoVO queryServiceItemAuditInfo(Long id)
    {
        // 查询服务项
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        // 查询店长
        List<SysUser> shopOwners = sysUserService.selectUserByRoleName("店长");

        // todo  key写死了
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("bus_car_package")
                .singleResult();
        // 3000 阈值 从流程图xml获取，前端页面不用写死了
        // 阈值也是可以变化，通过变量设置，从表中获取整个阈值
        // BpmnModel对象：用来封装我们画的流程图 XML
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        // 从流程图xml获取阈值(折扣价)
        BigDecimal discountPrice = ActivitiesUtils.getDiscountPrice(bpmnModel, "bus_car_package");

        // 查询财务
        AuditInfoVO auditInfoVO = new AuditInfoVO();
        auditInfoVO.setBusServiceItem(busServiceItem);
        auditInfoVO.setShopOwners(shopOwners);

        auditInfoVO.setDiscountPrice(discountPrice);    // 设置阈值

        if(busServiceItem.getDiscountPrice().compareTo(discountPrice) >= 0){
            List<SysUser> finances = sysUserService.selectUserByRoleName("财务");
            auditInfoVO.setFinances(finances);
        }
        return auditInfoVO;
    }
}
